import 'dart:math';
import 'dart:ui' as ui;

import 'package:flame/events.dart';
import 'package:flame/game.dart';
import 'package:flame/sprite.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import '../day001/component.dart';
import 'component.dart';

class ClickGame extends FlameGame
    with PanDetector, KeyboardEvents, HasTappables, HasHoverables {
  final String clickSrc = 'click.png';
  late TouchIndicator touchIndicator;
  late ui.Image clickImage;
  late final GirlComponent girl;
  late Monster monster;

  @override
  void update(double dt) {
    super.update(dt);
    final Iterable<Bullet> bullets = children.whereType<Bullet>();
    for (Bullet bullet in bullets) {
      if (bullet.isRemoving) {
        continue;
      }
      if (monster.containsPoint(bullet.absoluteCenter)) {
        bullet.removeFromParent();
        monster.loss(10);
      }
    }
  }

  @override
  Future<void> onLoad() async {
    await images.load(clickSrc);
    clickImage = images.fromCache(clickSrc);
    girl = GirlComponent();
    add(girl);

    const String src = 'girl/girlCombine.png';
    await images.load(src);
    var image = images.fromCache(src);
    SpriteSheet sheet =
    SpriteSheet.fromColumnsAndRows(image: image, columns: 8, rows: 4);
    List<Sprite> sprites = List.generate(32, sheet.getSpriteById);
    SpriteAnimation animation =
    SpriteAnimation.spriteList(sprites, stepTime: 1 / 8, loop: true);
    Vector2 monsterSize = Vector2(164, 164);
    final double pY = Random().nextDouble() * size.y;
    final double pX = size.x - monsterSize.x / 2;
    monster = Monster(animation, monsterSize, Vector2(pX, pY));
    add(monster);
  }

  @override
  void onPanDown(DragDownInfo info) async {
    Vector2 target = info.eventPosition.global;
    add(TouchIndicator(position: target, image: clickImage));
    girl.toTarget(target);
  }

  double ds = 0;

  @override
  void onPanUpdate(DragUpdateInfo info) {
    ds += info.delta.global.length;
    if (ds > 10) {
      add(TouchIndicator(
          position: info.eventPosition.global, image: clickImage));
      ds = 0;
    }
  }

  @override
  KeyEventResult onKeyEvent(
      RawKeyEvent event, Set<LogicalKeyboardKey> keysPressed) {
    final isKeyDown = event is RawKeyDownEvent;
    if (event.logicalKey == LogicalKeyboardKey.keyA && isKeyDown) {
      girl.shoot();
    }
    return super.onKeyEvent(event, keysPressed);
  }
}
